﻿namespace Rialternative.DomainService
{
    using System;
    using System.ServiceModel.DomainServices.Server;
    using Rialternative.Infrastructure;

    /// <summary>
    /// Provides logic to create a domain service using dependency injection pattern.
    /// </summary>
    public class DomainServiceFactory : IDomainServiceFactory
    {
        /// <summary>
        /// Creates a new <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/> instance.
        /// </summary>
        /// <param name="domainServiceType">The <see cref="T:System.Type"/> of <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/> to create.</param>
        /// <param name="context">The current <see cref="T:System.ServiceModel.DomainServices.Server.DomainServiceContext"/>.</param>
        /// <returns>
        /// A <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/> instance.
        /// </returns>
        public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
        {
            DomainService domainService = IOCProvider.Container.ResolveType(domainServiceType) as DomainService;
            domainService.Initialize(context);

            return domainService;
        }

        /// <summary>
        /// Releases an existing <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/> instance.
        /// </summary>
        /// <param name="domainService">The <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/> instance to release.</param>
        public void ReleaseDomainService(DomainService domainService)
        {
            if (domainService != null)
            {
                domainService.Dispose();
            }
        }
    }
}
